import plugin from '../../lib/plugins/plugin.js';
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { exec } = require("child_process");
import fetch from "node-fetch";
import fs from 'fs';
import path from 'path';

let update = 'https://raw.githubusercontent.com/T060925ZX/JiaoziJs/refs/heads/main/plugins.js';
const dirPath = 'plugins/example/';

fs.access(path.join(dirPath, '插件安装器Pro.js'), fs.constants.F_OK, (err) => {
    if (err) {
        console.log('文件不存在，正在下载...');
        const curlCommand = `curl -o ${path.join(dirPath, '插件安装器Pro.js')} ${update}`;
        exec(curlCommand, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行curl命令出错: ${error}`);
            }
            console.log('下载完成:', stdout);
        });
    } else {
        return false;
    }
});

/**
 * 作者：Jiaozi饺子(1602833550)
 */

export class example2 extends plugin {
    constructor () {
      super({
        name: '插件管理器update',
        dsc: '插件管理器update@Jiaozi',
        event: 'message',
        priority: -1,
        rule: [
          {
            reg: '^#更新插件(安装|管理)器$',
            fnc: 'update'
          }
        ]
      });
    }

    async update(e) {
        let plugin_name_prefix = '插件安装器';
        try {
          const files = fs.readdirSync(dirPath);
          
          // 遍历目录，删除所有以“插件安装器”开头的文件
          files.forEach(file => {
              if (file.startsWith(plugin_name_prefix)) {
                  fs.rmSync(path.join(dirPath, file), { recursive: true, force: true });
              }
          });

        } catch (err) {
            await e.reply(`插件更新失败！\n${err.message}`);
            return true;
        }
        
        await e.reply(`本次更新通道${update}，正在更新中……`);
        let com = `curl -o ${path.join(dirPath, '插件安装器Pro.js')} ${update} && rm -f ${path.join(dirPath, 'up.js')}`;
        
        let com_result = await this.execSyncc(com, { encoding: 'buffer' });
        if(com_result.error) {
            await e.reply(`安装时出现错误！\n${com_result.error.message}`);
            return true;
        }
        await e.reply(`插件更新成功！重启后生效`);
    }

    async execSyncc(cmd) {
      return new Promise((resolve, reject) => {
        exec(cmd, { windowsHide: true }, (error, stdout, stderr) => {
          resolve({ error, stdout, stderr });
        });
      });
    }
}
